//
//  NewsCollectionCell.m
//  花花时尚
//
//  Created by 霍文轩 on 15/8/20.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//


/*
 *
 *
 */
#import "DressCollectionCell.h"
#import "NewsTableCell.h"
#import "AsyncGETConnection.h"
#import "UIImageView+WebCache.h"
#import "FashionNewsModel.h"

#import "FashionDetailView.h"
#import "GiFHUD.h"
#import "MJRefresh.h"


@interface DressCollectionCell() <UITableViewDataSource,UITableViewDelegate,FashionDetailViewDelegate>
//{
//    NSInteger selectedRow; // 标识是否被选中
//}
@property (nonatomic,retain) UITableView * table;
@property (nonatomic,retain) UIImageView * upImageView;
@property (nonatomic,retain) UIImageView * downImageView;
@property (nonatomic,retain) NSMutableArray * tableArray;

@property (nonatomic,assign) NSInteger currentPage;

@end

#define kCellHeight 215;

@implementation DressCollectionCell
-(void)dealloc{
    [_table release];
    [_upImageView release];
    [_downImageView release];
    [_tableArray release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.currentPage = 1;
        [GiFHUD setGifWithImageName:@"33333333333.gif"];
        [GiFHUD show];
//        selectedRow = -1;
        [self loadModelFromLocal];
        
    }
    return self;
}
// 首先从文件夹读取
-(void)loadModelFromLocal{
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    NSArray * listArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/news/%@",path,@"dress"] error:nil];
    for (NSString * fileName in listArray) { // fileName为每个文件的文件名
        NSData * data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/news/dress/%@",path,fileName]];
        FashionNewsModel * model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [_tableArray addObject:model];
    }
    
    [self createTable];
    [self reloadDataFromNetwork];
}
-(void)reloadDataFromNetwork{
//    MBProgressHUD * mb = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
//    [self addSubview:mb];
//    mb.userInteractionEnabled = NO;
//    mb.labelText = @"加载中...";
//    [mb show:YES];
//    [mb release];
    
    // 先进行网络请求再创建tableView
    [AsyncGETConnection asyncConnectionWithURLString:@"http://app.ellechina.com/?app=rss&controller=elleplus&action=elleplus_channellist&catid=434&pagenum=1&num=10" parmaters:nil block:^(NSData *data) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
//        [mb removeFromSuperview];
        [GiFHUD dismiss];
        [self.tableArray removeAllObjects];
        
        NSInteger i = 0;
        for (NSDictionary * subDic in [NSArray arrayWithArray:[dic objectForKey:@"data"]]) {
            FashionNewsModel * model = [[FashionNewsModel alloc] init];
            [model setValuesForKeysWithDictionary:subDic];
            [self.tableArray addObject:model];
            
            // 存入文件
            NSString * path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
            NSData * data = [NSKeyedArchiver archivedDataWithRootObject:model];
            path = [NSString stringWithFormat:@"%@/news/dress/%.2ld",path,(long)i]; // 要按照加入的顺序命名，而不能按照id命名，会造成读取顺序不一致
            [data writeToFile:path atomically:YES];
            i++;
            
            [model release];
        }
        [_table reloadData];
    }];
}
-(void)createTable{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];
    _table.contentInset = UIEdgeInsetsMake(44+40, 0, 0, 0); // 在上方留出空白
    _table.separatorStyle = UITableViewCellSeparatorStyleNone;
    _table.backgroundColor = [UIColor clearColor];
    
    _table.delegate = self;
    _table.dataSource = self;
    [self.contentView addSubview:_table];
    
    // 上拉加载
    [_table addFooterWithCallback:^{
        // 如果到了第10页，显示没有更多数据，不能加载数据
        if(_currentPage == 10){
            [_table setFooterRefreshingText:@"没有更多数据"];
            [_table footerEndRefreshing];
        }
        if(_currentPage < 10){
            [AsyncGETConnection asyncConnectionWithURLString:[NSString stringWithFormat:@"http://app.ellechina.com/?app=rss&controller=elleplus&action=elleplus_channellist&catid=434&pagenum=%ld&num=10",(long)_currentPage+1] parmaters:nil block:^(NSData *data) {
                
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                for (NSDictionary * subDic in [NSArray arrayWithArray:[dic objectForKey:@"data"]]) {
                    FashionNewsModel * model = [[FashionNewsModel alloc] init];
                    [model setValuesForKeysWithDictionary:subDic];
                    [self.tableArray addObject:model];
                    [model release];
                }
                
                self.currentPage++;
                [_table reloadData];
                [_table footerEndRefreshing];
            }];
        }
    }];
    
    [_table release];
}

#pragma mark - UITableView协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _tableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * defaultCellIdentify = @"defaultCell";
    NewsTableCell * cell = [tableView dequeueReusableCellWithIdentifier:defaultCellIdentify];
    if(!cell){
        cell = [[NewsTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:defaultCellIdentify];
    }
    [cell sendMessageWithModel:[_tableArray objectAtIndex:indexPath.row]];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if(indexPath.row == selectedRow){ 
//        return 200;
//    }
    return kCellHeight;
}
#pragma  mark - 当某一个cell被选中时，创建详情页
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsTableCell * cell = (NewsTableCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    // 根据contentOffSet和indexPath判断cell在屏幕上的的位置
    CGFloat cellHeightInScreen = tableView.contentOffset.y - indexPath.row*kCellHeight;
    
    float scaleIniPhone6 = 377.0/667.0; // 以iPhone6的比例为标准计算当前的高度
    float originalImageHeight =  [UIScreen mainScreen].bounds.size.height*scaleIniPhone6;
    
    FashionNewsModel * model = [_tableArray objectAtIndex:indexPath.row];
    
    FashionDetailView * fashionDetail = [[FashionDetailView alloc] initWithFrame:[UIScreen mainScreen].bounds image:cell.originalImage imageRect:CGRectMake(0, -cellHeightInScreen, self.frame.size.width, originalImageHeight) model:model];
    fashionDetail.delegate = self;
    [self.superview.superview addSubview:fashionDetail];
    [self.delegate clickDressIndex:indexPath];
}
-(void)showShareViewWithTitle:(NSString *)title image:(UIImage *)image urlString:(NSString *)urlString{
    [self.delegate showShareViewWithTitle:title image:image urlString:urlString];
}
-(void)detailWillDisappear{
    // 这里不需要重写，给收藏界面的方法
     [[NSNotificationCenter defaultCenter] postNotificationName:@"tabBarAppearNotification" object:nil];
}
@end
